const { DB } = require('lsd-db')

const crypto = require('crypto')
const uuid = require('uuid');
import BaseResult from '../lib/BaseResult.js'
var redis = require("redis");
var client = redis.createClient();

client.on("error", function(err) {
    console.log("Error " + err);
});

class User {

    static async login(ctx) {
        let db = new DB('user');
        const md5 = crypto.createHash("md5");
        let data = ctx.request.body;
        data.password = md5.update(data.password).digest('hex');
        data = await db.debug(true).query().select(data).end();
        if (data.length > 0) {
            // let sign = new Buffer(JSON.stringify({
            //     userName: data[0].userName,
            //     userid: data[0].id
            // }));
            let apps = await new DB('app').query().select().end();
            // const cToken = crypto.createHash("md5");
            let token = uuid.v1();
            client.set(token, JSON.stringify({
                userName: data[0].userName,
                id: data[0].id
            }), redis.print);
            // ctx.session[token]= {
            //     userName: data[0].userName,
            //     id: data[0].id
            // }
            // var btoken = new Buffer(sign);
            // var ssign = btoken.toString('base64');
            let sso = [];
            apps.forEach(e => {
                sso.push(e.sso + '?token=' + token);
            });
            ctx.body = new BaseResult(0, null, {
                token: token,
                sso: sso
            })
        } else {
            ctx.body = new BaseResult(1, '登陆失败，用户名或密码错误', null)
        }

    }
}
export default User;